package cn.ilikes.tools.nosql.jpa.metadatas.processor.validators;

import java.lang.reflect.Field;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

import org.slf4j.Logger;

import cn.ilikes.tools.logs.Loggerfactory;
import cn.ilikes.tools.nosql.jpa.annotations.IndexColumn;
import cn.ilikes.tools.nosql.jpa.metadatas.EntityMetaData;

/**
 * 实体字段验证 1： 是否包含了 @ID 2： 当有@IndexColumn ,@ OneToMany ,@OneToOne 时必须有
 * 
 * @author fack
 * 
 */
public class EntityFieldValidator extends AbEntityValidator implements EntityValidator {

	private Logger logger = Loggerfactory.instance(EntityIndexValidator.class);

	@Override
	public boolean entityValidator(Class<?> clazz, EntityMetaData entityMetaData) throws EntityValidatorException {

		Field[] fs = clazz.getDeclaredFields();
		boolean isId = false;
		for (Field f : fs) {
			if (f.isAnnotationPresent(Id.class)) {
				if (!f.isAnnotationPresent(IndexColumn.class)) {
					throwEntityValidatorException(logger, "this entity  : " + clazz.getSimpleName() + " have @Id  but  not set  @IndexColumn  ! ");
				}
				isId = true;
			}
			if (f.isAnnotationPresent(Column.class)) {
				Column column = f.getAnnotation(Column.class);
				//				if (column.name() == null || column.name().equals(""))
				//					throwEntityValidatorException(logger, "this entity  : " + clazz.getSimpleName() + " @Column name not set ! ");
			}

			if (f.isAnnotationPresent(IndexColumn.class)) {
				if (f.isAnnotationPresent(Column.class) || f.isAnnotationPresent(OneToMany.class) || f.isAnnotationPresent(OneToOne.class)
						|| f.isAnnotationPresent(ManyToOne.class) || f.isAnnotationPresent(Id.class)) {
				} else
					throwEntityValidatorException(logger, "this entity  : " + clazz.getSimpleName()
							+ " have  @IndexColumn but not have @Column  or @OneToMany or @ OneToOne  ");

			}
		}
		if (!isId) {
			throwEntityValidatorException(logger, "this entity  : " + clazz.getSimpleName() + " not find @Id");
		}

		return true;
	}
}
